//
//  CTCPublishArticleVC.m
//  ConsultantVersion
//
//  Created by 小龙 on 2016/12/8.
//  Copyright © 2017年 com.jieshuibao1. All rights reserved.
//

#import <WebKit/WebKit.h>
#import "CTCPublishArticleVC.h"
//#import "JSBOriginalModel.h"
#import "BWHTextView.h"
#import "CTCArticleTagModel.h"
#import "TTGTextTagCollectionView.h"
#import "TTGTagCollectionView.h"




#define kScrollViewContsize @"contentSize"

@interface CTCPublishArticleVC ()<TTGTextTagCollectionViewDelegate,
                                                UITextFieldDelegate,
                                                UITextViewDelegate,
                                                UIScrollViewDelegate
                                                >

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UITextField *titleView;

@property (weak, nonatomic) IBOutlet BWHTextView *introductionTextView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentHeight;
/**
 tag部分
 */
@property (weak, nonatomic) IBOutlet TTGTextTagCollectionView *tagView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagViewHeight;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSMutableArray<CTCArticleTagModel *> *tags;



@end

@implementation CTCPublishArticleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    [self setupTagView];
    
    self.introductionTextView.placeHolderText = @"请输入文章内容";
    self.introductionTextView.delegate = self;
    self.introductionTextView.scrollEnabled = NO;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_tagView reload];

}


#pragma mark - 导航
- (void)setupNav
{
    self.title = @"发布文章";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(sendCommit)];
}

- (void)dismiss
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}




#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat height = [self heightForString:textView andWidth:textView.width];
    self.contentHeight.constant = MAX(height + 10, 240);
    
}

- (float)heightForString:(UITextView *)textView andWidth:(float)width
{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}


- (void)sendCommit
{
    
    if ([NSString isBlank:_titleView.text]) {
        [MBProgressHUD showErrorMessage:@"请输入标题"];
        return;
    }
    
    
    if ([NSString isBlank:_titleView.text]) {
        [MBProgressHUD showErrorMessage:@"请输入标题"];
        return;
    }
    
    if (_titleView.text.length > 30) {
        [MBProgressHUD showErrorMessage:@"标题过长"];
        return;
    }
    
    if ([NSString isBlank:_introductionTextView.text]) {
        [MBProgressHUD showErrorMessage:@"请输入文章内容"];
        return;
    }
    
    if (self.selectIndex < 0) {
        [MBProgressHUD showErrorMessage:@"请选择标签"];
        return;
    }
    
    [self.introductionTextView resignFirstResponder];
    
    [self send];
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认发布" message:@"您的文章将展示在财税圈中 " preferredStyle:UIAlertControllerStyleAlert];
//    
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    
//    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self send];
//    }];
//    
//    [alert addAction:cancel];
//    [alert addAction:sure];
//    
//    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)send
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"title"] = _titleView.text;
    params[@"content"] = _introductionTextView.text;
    CTCArticleTagModel *selectModel = self.tags[_selectIndex];
    params[@"labelId"] = selectModel.uuid;
    
    DeLog(@"param %@", params);

    [MBProgressHUD showAnimationHUD];;
    [RequestTool POST:kPublishArticleUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        DeLog(@"发表文章---- responseObject：%@", responseObject);
        
        NSInteger code = [responseObject[@"code"] integerValue];
        
        if (code == 1) {
            [MBProgressHUD showSuccessMessage:responseObject[@"des"]];
            
            if (self.pulicSuccessDismissBlock) {
                self.pulicSuccessDismissBlock(selectModel.uuid);
            }
            [self dismiss];
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            
            if (code == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         DeLog(@"发布文章----error：%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
    }];
    
}

#pragma mark - 标签
- (void)setupTagView
{
    _tagView.delegate = self;
    _tagView.translatesAutoresizingMaskIntoConstraints = NO;

    _tagView.defaultConfig.tagTextFont = [UIFont systemFontOfSize:13.0f];
    _tagView.defaultConfig.tagExtraSpace = CGSizeMake(15, 15);
    
    UIColor *defaultColor = [UIColor whiteColor];
    UIColor *selectColor = HEXCOLOR(0x2079ef);
    _tagView.defaultConfig.tagTextColor = selectColor;
    _tagView.defaultConfig.tagBackgroundColor = defaultColor;
    _tagView.defaultConfig.tagCornerRadius = 8.0f;
    
    _tagView.defaultConfig.tagSelectedTextColor = defaultColor;
    _tagView.defaultConfig.tagSelectedBackgroundColor = selectColor;
    _tagView.defaultConfig.tagSelectedCornerRadius = 8.0f;
    
    _tagView.defaultConfig.tagBorderWidth = 1;
    _tagView.defaultConfig.tagBorderColor = selectColor;
//    _tagView.defaultConfig.tagSelectedBorderColor = selectColor;
    
    _tagView.horizontalSpacing = 8;
    _tagView.verticalSpacing = 8;
    
//    [_tagView setTagAtIndex:0 selected:YES];
    
    // 请求标签
    [self loadTags];
}

- (void)loadTags
{
    [MBProgressHUD showAnimationHUD];;
    [RequestTool POST:kArticleTagListUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        CTCArticleTagListModel *listModel = [CTCArticleTagListModel yy_modelWithJSON:responseObject];
        if ([listModel.code integerValue] == 1) {
            [MBProgressHUD hideHUD];
            [self.tags addObjectsFromArray:listModel.articleTagArr];
            [self resetTagViewTags];
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if ([listModel.code integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadTags];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"标签列表---error:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
    }];
    
}

- (void)resetTagViewTags
{
    self.selectIndex = -1;
    
    [self.tagView removeAllTags];
    for (CTCArticleTagModel *tag in self.tags) {
        [self.tagView addTag:tag.name];
    }
    [self.tagView reload];
    
}


#pragma mark - TTGTextTagCollectionViewDelegate
- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView didTapTag:(NSString *)tagText atIndex:(NSUInteger)index selected:(BOOL)selected
{
    if (self.selectIndex > -1) {
        [textTagCollectionView setTagAtIndex:self.selectIndex selected:NO];
    }
    
    self.selectIndex = selected ? index : -1;
}

- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView updateContentSize:(CGSize)contentSize
{
    if (self.tagViewHeight.constant != contentSize.height) {
        self.tagViewHeight.constant = contentSize.height;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view setNeedsLayout];
        });
    }
    
}

#pragma mark - 懒加载
- (NSMutableArray *)tags
{
    if (!_tags) {
        _tags = [NSMutableArray array];
    }
    return _tags;
}

@end
